package com.chennan.project.domain.service.impl;

import com.chennan.common.domian.ResponseData;
import com.chennan.project.api.rest.controller.dto.HandleClickDTO;
import com.chennan.rebbitmq.leading.consumer.MyStreamClient;
import com.chennan.rebbitmq.leading.producer.MyStreamOutput;
import com.chennan.redis.domain.service.RedisServiceComplete;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author chennan
 * @createTime 2021年08月03日 14:50:00
 */
//@Service
public class WuzqServiceImpl {

    public static BlockingQueue<String> users = new LinkedBlockingDeque<>();

    @Autowired
    private MyStreamOutput myStreamOutput;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private RedisServiceComplete redisServiceComplete;

    @Qualifier("customsThreadPool")
    @Autowired
    private Executor executor;

    public ResponseData luozi(HandleClickDTO handleClickDTO){
        boolean send = myStreamOutput.wuzqToMessageChannel().send(MessageBuilder.withPayload(handleClickDTO).setHeader("headerTag", "wuzhiqi").build());
        return send?ResponseData.SCESSES:ResponseData.ERROR;
    }

    @StreamListener(value = MyStreamClient.DATA_TO_WUZHIQ_INPUT)
    public void excelExportSlow(@Payload HandleClickDTO handleClickDTO, @Header("headerTag") String headerTag) {
        System.out.println("接受到了五子棋消息！！！！"+handleClickDTO);
        String s = redisServiceComplete.get(handleClickDTO.getUsername());
        messagingTemplate.convertAndSendToUser(s, "/queue/wuziqi",handleClickDTO);
    }

    public void initWuziqi(String username) {
        String poll = users.poll();
        if(StringUtils.isEmpty(poll)){
            users.offer(username);
        }else{
            redisServiceComplete.setNX(username,poll,600);
            redisServiceComplete.setNX(poll,username,600);
            messagingTemplate.convertAndSendToUser(username, "/queue/wuziqi","1");
            messagingTemplate.convertAndSendToUser(poll, "/queue/wuziqi","0");
        }
//        executor.execute(()->{
//            String poll = users.poll();
//            while (StringUtils.isEmpty(poll)){
//
//            }
//        });
    }
}
